// 引入express框架
var express = require('express');
// 创建路由对象
var router = express.Router();
let afterSalesDemandModel = require('../db/AfterSalesDemand');
const { v4: uuidv4 } = require('uuid');

/* GET home page. */
// 首页路由，渲染index页面
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});

// 获取售后列表（支持多条件搜索和分页）
router.get('/list', async function (req, res, next) {
    try {
        let {
            page = 1,
            pageSize = 10,
            name,      // 售后需求名称
            type,      // 需求类型
            charge,    // 是否收费
            status,    // 状态
            keyword    // 搜索关键词
        } = req.query;
        page = parseInt(page);
        pageSize = parseInt(pageSize);

        // 构建查询条件
        let query = {};
        if (type) query.type = type;
        if (charge) query.charge = charge;
        if (status) query.status = status;

        // 多字段模糊搜索
        if (keyword) {
            query.$or = [
                { name: { $regex: keyword, $options: 'i' } },
                { remark: { $regex: keyword, $options: 'i' } },
                { creator: { $regex: keyword, $options: 'i' } }
            ];
        } else if (name) {
            // 单独按名称模糊
            query.name = { $regex: name, $options: 'i' };
        }

        // 查询数据
        const list = await afterSalesDemandModel.find(query)
            .skip((page - 1) * pageSize)
            .limit(pageSize)
            .sort({ createTime: -1 });

        const total = await afterSalesDemandModel.countDocuments(query);

        res.json({
            code: 200,
            data: {
                list,
                total,
                page,
                pageSize
            }
        });
    } catch (err) {
        res.json({ code: 500, msg: '获取失败', error: err.message });
    }
});

// 新增售后需求记录
router.post('/add', async function (req, res, next) {
    try {
        let demand = req.body;
        if (!demand.id) demand.id = uuidv4();
        if (!demand.createTime) demand.createTime = new Date().toLocaleString();
        if (!demand.updateTime) demand.updateTime = new Date().toLocaleString();

        // 类型转换
        if (demand.planHour) demand.planHour = Number(demand.planHour);
        if (demand.actualHour) demand.actualHour = Number(demand.actualHour);

        const data = await afterSalesDemandModel.create(demand);
        res.json({
            code: 200,
            data: data,
            msg: '添加成功'
        });
    } catch (err) {
        console.error('写入数据库失败:', err);
        res.json({
            code: 500,
            msg: '添加失败',
            error: err.message
        });
    }
});

// 更新售后需求记录
router.post('/update', function (req, res, next) {
    let demand = req.body;
    if (!demand.id) return res.json({ code: 400, msg: '缺少id' });
    
    demand.updateTime = new Date().toLocaleString();
    
    afterSalesDemandModel.updateOne({ id: demand.id }, demand).then(function (data) {
        res.json({
            code: 200,
            data: data,
            msg: '更新成功'
        });
    }).catch(err => {
        res.json({
            code: 500,
            msg: '更新失败',
            error: err.message
        });
    });
});

// 删除售后需求记录
router.post('/delete', function (req, res, next) {
    let demand = req.body;
    if (!demand.id) return res.json({ code: 400, msg: '缺少id' });
    
    afterSalesDemandModel.deleteOne({ id: demand.id }).then(function (data) {
        res.json({
            code: 200,
            data: data,
            msg: '删除成功'
        });
    }).catch(err => {
        res.json({
            code: 500,
            msg: '删除失败',
            error: err.message
        });
    });
});

// 批量删除售后需求记录
router.post('/batchDelete', function (req, res, next) {
    let { ids } = req.body;
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.json({ code: 400, msg: '缺少要删除的ID列表' });
    }
    
    afterSalesDemandModel.deleteMany({ id: { $in: ids } }).then(function (data) {
        res.json({
            code: 200,
            data: data,
            msg: `成功删除${data.deletedCount}条记录`
        });
    }).catch(err => {
        res.json({
            code: 500,
            msg: '批量删除失败',
            error: err.message
        });
    });
});

// 搜索售后需求记录
router.post('/search', function (req, res, next) {
    let { keyword, type, charge, status, projectId, page = 1, pageSize = 10 } = req.body;
    const skip = (page - 1) * pageSize;
    
    let query = {};
    
    // 关键词搜索
    if (keyword) {
        query.$or = [
            { name: { $regex: keyword, $options: 'i' } },
            { remark: { $regex: keyword, $options: 'i' } },
            { creator: { $regex: keyword, $options: 'i' } },
            { assignee: { $regex: keyword, $options: 'i' } }
        ];
    }
    
    // 类型筛选
    if (type) {
        query.type = type;
    }
    
    // 是否收费筛选
    if (charge) {
        query.charge = charge;
    }
    
    // 状态筛选
    if (status) {
        query.status = status;
    }
    
    // 项目ID筛选
    if (projectId) {
        query.projectId = projectId;
    }
    
    afterSalesDemandModel.find(query)
        .skip(skip)
        .limit(parseInt(pageSize))
        .sort({ createTime: -1 })
        .then(function (data) {
            afterSalesDemandModel.countDocuments(query).then(function (total) {
                res.json({
                    code: 200,
                    data: {
                        list: data,
                        total: total,
                        page: parseInt(page),
                        pageSize: parseInt(pageSize)
                    },
                    msg: '查询成功'
                });
            });
        }).catch(err => {
            res.json({
                code: 500,
                msg: '查询失败',
                error: err.message
            });
        });
});

// 根据ID获取单条记录
router.get('/detail/:id', function (req, res, next) {
    let { id } = req.params;
    
    afterSalesDemandModel.findOne({ id: id }).then(function (data) {
        if (data) {
            res.json({
                code: 200,
                data: data,
                msg: '获取成功'
            });
        } else {
            res.json({
                code: 404,
                msg: '记录不存在'
            });
        }
    }).catch(err => {
        res.json({
            code: 500,
            msg: '获取失败',
            error: err.message
        });
    });
});

// 获取需求类型统计
router.get('/typeStats', function (req, res, next) {
    const { projectId } = req.query;
    let query = {};
    if (projectId) {
        query.projectId = projectId;
    }
    
    afterSalesDemandModel.aggregate([
        { $match: query },
        { $group: { _id: '$type', count: { $sum: 1 } } }
    ]).then(function (data) {
        res.json({
            code: 200,
            data: data,
            msg: '统计成功'
        });
    }).catch(err => {
        res.json({
            code: 500,
            msg: '统计失败',
            error: err.message
        });
    });
});

// 导出路由对象
module.exports = router;